import { useModuleStore } from '@/store/moduleStore'

export default function (
  whereSelectList: any,
  actionType: any,
  fieldSelected: any,
  tableSelectAssociation: any,
  isMutilTable: any,
  sqlStr: any,
  orderSelectList: any,
  fieldList: any,

  // 更新
  updateCheckBoxList: any,
  upDateFieldList: any,
  // 删除
  physicsDelete: any,
  // 插入
  insertCheckBoxList: any,
  insertFieldList: any
) {
  const moduleStore = useModuleStore()

  /**
   * 重建SQL查询语句
   * 该函数用于根据当前的选择和配置重新构建SQL查询语句
   */
  function reBuildSql () {
    // 清空SQL字符串
    sqlStr.value = ''

    // where 语句构建
    const { whereSqlStrArr, tWhereSqlStrArr } = buildWhereSql(
      whereSelectList.value
    )

    // 如果是查询操作
    if (actionType.value == 'select' || actionType.value == 'selectOne') {
      let fieldsSelectSqlStr = []
      // 遍历选中的字段,生成查询字段字符串
      for (let i = 0; i < fieldSelected.value.length; i++) {
        // 如果字段数组不为空
        if (
          fieldSelected.value[i].fields &&
          fieldSelected.value[i].fields.length
        ) {
          let fsqArr: any[] = []
          // 遍历每个字段
          fieldSelected.value[i].fields.forEach(
            (item: any, itemIndex: number) => {
              // 查找字段别名
              let aliasName = fieldSelected.value[
                i
              ].fieldAliasNameMapArray.find(
                (i: any) => i.name == item
              )?.aliasName

              // 构建字段字符串，如果有别名则添加别名
              // 获取item类型，如果是datetime 的 改为 date_format(update_time,'%Y-%m-%d %H:%i:%s') as updateTime
              let f = moduleStore.currentModule.field.some((i: any) => {
                return i.type == 'datetime' && item == i.name
              })
              let fStr = ''
              if (f) {
                fStr = `&emsp;&emsp;date_format(${item},'%Y-%m-%d %H:%i:%s')${
                  aliasName ? ` as ${aliasName}` : ''
                }`
              } else {
                fStr = `&emsp;&emsp;${item}${
                  aliasName ? ` as ${aliasName}` : ''
                }`
              }

              fsqArr.push(fStr)
            }
          )
          // 将字段字符串数组加入总字段字符串数组
          fieldsSelectSqlStr.push(fsqArr.join(',<br/>'))
        }
      }

      let tableAssociationStrArr = []
      // 遍历关联数组，生成关联字符串
      for (let i = 0; i < tableSelectAssociation.value.length; i++) {
        let item = tableSelectAssociation.value[i]
        let str = ''
        // 如果不是多表关联，则直接添加表名
        if (!isMutilTable.value) {
          str = `&emsp;&emsp;${item.tableA}`
          tableAssociationStrArr.push(str)
        } else {
          // 处理隐式连接
          if (item.association == 'IMPLICIT JOIN') {
            if ((!item.association || !item.tableA || !item.tableB) && i == 0)
              continue
            if ((!item.association || !item.tableB) && i > 0) continue
            if (i == 0) {
              str = `${item.tableA}, ${item.tableB}`
            } else {
              str = `, ${item.tableB}`
            }
            tableAssociationStrArr.push(str)
            continue
          } else {
            // 处理显式连接
            if (
              (!item.association ||
                !item.tableA ||
                !item.tableB ||
                !item.fieldA ||
                !item.fieldB ||
                item.fieldA.length == 0 ||
                item.fieldB.length == 0) &&
              i == 0
            )
              continue
            if (
              (!item.association ||
                !item.tableB ||
                !item.fieldB ||
                item.fieldB.length == 0) &&
              i > 0
            )
              continue
            if (i == 0) {
              str = `${item.tableA} ${item.association} ${item.tableB} ON ${item.fieldA[0]}.${item.fieldA[1]} = ${item.fieldB[0]}.${item.fieldB[1]}`
            } else {
              str = `${item.association} ${item.tableB} ON ${item.fieldA[0]}.${item.fieldA[1]} = ${item.fieldB[0]}.${item.fieldB[1]}`
            }
            tableAssociationStrArr.push(str)
          }
        }
      }

      //order by语句
      let orderSqlStrArr = [] as any[]
      orderSelectList.value.forEach((item: any) => {
        if (item.field.length == 0) return
        orderSqlStrArr.push(`&emsp;&emsp;${item.field} ${item.orderType}`)
      })
      // 构建SQL查询语句
      sqlStr.value = `select <br/>${
        fieldsSelectSqlStr.length == 0
          ? '&emsp;&emsp;*<br/>'
          : fieldsSelectSqlStr.join(',') + '<br/>'
      } from <br/>${tableAssociationStrArr.join(' ')}
       <br/> where <br/>&emsp;&emsp;del_flag = 0 <br/>
       ${whereSqlStrArr.length > 0 ? tWhereSqlStrArr.join(' ') : ' <br/>'}${
        orderSelectList.value.length > 0
          ? 'order by <br/>' + orderSqlStrArr.join(',<br/>')
          : '<br/>'
      }<br/>`
    }
    // 如果是更新操作
    if (actionType.value == 'update') {
      let uArr = upDateFieldList.value.filter((item: any) => {
        return updateCheckBoxList.value.includes(item.value)
      })
      let uStr = ''
      uArr.forEach((item: any) => {
        if (item.isParamName == true) {
          uStr += `&emsp;&emsp;[[${item.value} = '{{${item.aliasName}}}',]] <br/>`
        } else if (item.isParamName === false) {
          uStr += `&emsp;&emsp;${item.value} = '${item.aliasName}', <br/>`
        }
      })

      sqlStr.value = `update <br/>&emsp;&emsp;${
        tableSelectAssociation.value[0].tableA
      } <br/>set <br/>${
        uStr ? uStr + ' ' : ' '
      }&emsp;&emsp;del_flag = 0 <br/> where <br/>&emsp;&emsp;del_flag = 0 <br/>${
        whereSqlStrArr.length > 0 ? tWhereSqlStrArr.join(' ') : ''
      }`
    }
    // 如果是删除操作
    if (actionType.value == 'delete') {
      if (physicsDelete.value == true) {
        sqlStr.value = `delete <br/>from <br/>&emsp;&emsp;${
          tableSelectAssociation.value[0].tableA
        } <br/>where <br/>&emsp;&emsp;del_flag = 0 <br/>${tWhereSqlStrArr.join(
          ' '
        )}`
      } else {
        sqlStr.value = `update <br/>&emsp;&emsp;${
          tableSelectAssociation.value[0].tableA
        } <br/>set <br/>&emsp;&emsp;del_flag = 1 <br/>where <br/>&emsp;&emsp;del_flag = 0 <br/>${tWhereSqlStrArr.join(
          ' '
        )}`
      }
    }
    // 如果是插入操作
    if (actionType.value == 'insert') {
      let keys = insertCheckBoxList.value.join(', ')
      let iArr = [] as any
      insertCheckBoxList.value.forEach((i: any) => {
        insertFieldList.value.forEach((item: any) => {
          if (item.value == i) {
            iArr.push(item)
          }
        })
      })

      let iStr = ''
      iArr.forEach((item: any) => {
        if (item.isParamName == true) {
          iStr += `&emsp;&emsp;[[${item.value},]]<br/>`
        } else if (item.isParamName === false) {
          iStr += `&emsp;&emsp;${item.value},<br/>`
        }
      })
      sqlStr.value = `insert into <br/>&emsp;&emsp;${
        tableSelectAssociation.value[0].tableA
      } ( ${keys} ) <br/>values <br/>&emsp;&emsp;(${iArr.map((item: any) => {
        if (item.isParamName == true) {
          return ` '{{${item.aliasName}}}' `
        } else if (item.isParamName === false) {
          return ` '${item.aliasName}' `
        }
      })})`
    }
  }

  function buildWhereSql (whereSelectList: any) {
    let whereSqlStrArr = []
    let tWhereSqlStrArr = []
    for (let i = 0; i < whereSelectList.length; i++) {
      // 遍历 whereSelectList 数组
      let item = whereSelectList[i]
      let str = ''
      // 如果字段为空或没有操作符，则跳过当前循环
      if (item.field.length == 0 || !item.operator) continue
      // 处理非特殊操作符的情况
      if (
        item.operator != 'IN' &&
        item.operator != 'BETWEEN' &&
        item.operator != 'IS NULL' &&
        item.operator != 'IS NOT NULL'
      ) {
        if (item.isParamName) {
          str = `${item.field} ${item.operator} '{{${item.valueA}}}'`
        } else {
          str = `${item.field} ${item.operator} '${item.valueA}'`
        }
      }
      // 处理 IN 操作符
      if (item.operator == 'IN') {
        if (item.isParamName) {
          str = `${item.field} IN ('{{${item.valueA}}}')`
        } else {
          str = `${item.field} IN ('${item.valueA}')`
        }
      }
      // 处理 BETWEEN 操作符
      if (item.operator == 'BETWEEN') {
        if (item.valueA && item.valueB) {
          if (item.isParamName) {
            str = `${item.field} BETWEEN '{{${item.valueA}}}' AND '{{${item.valueB}}}'`
          } else {
            str = `${item.field} BETWEEN '${item.valueA}' AND '${item.valueB}'`
          }
        }
      }
      // 处理 IS NULL 和 IS NOT NULL 操作符
      if (item.operator == 'IS NULL' || item.operator == 'IS NOT NULL') {
        str = `${item.field} ${item.operator}`
      }
      // 处理 LIKE 操作符
      if (item.operator == 'LIKE') {
        if (item.isParamName) {
          str = `${item.field} LIKE '%{{${item.valueA}}}%'`
        } else {
          str = `${item.field} LIKE '%${item.valueA}%'`
        }
      }

      // 将构建的 SQL 字符串添加到 whereSqlStrArr 数组中
      whereSqlStrArr.push(str)

      // 语句优先级处理
    }
    tWhereSqlStrArr = JSON.parse(JSON.stringify(whereSqlStrArr))
    // 遍历 tWhereSqlStrArr 数组，为每个元素添加逻辑运算符
    tWhereSqlStrArr.forEach((item: any, index: number) => {
      // 如果是变量名，加[[]]
      if (whereSelectList[index].isParamName) {
        // 如果不是第一条语句，语句最前方添加逻辑运算符
        if (index > 0) {
          tWhereSqlStrArr[
            index
          ] = `&emsp;&emsp;[[${whereSelectList[index].logic} ${item}]] <br/>`
        } else {
          tWhereSqlStrArr[index] = `&emsp;&emsp;[[AND ${item}]] <br/>`
        }
      } else {
        // 如果不是第一条语句，语句最前方添加逻辑运算符
        if (index > 0) {
          tWhereSqlStrArr[
            index
          ] = `&emsp;&emsp;${whereSelectList[index].logic} ${item} <br/>`
        } else {
          tWhereSqlStrArr[index] = `&emsp;&emsp;AND ${item} <br/>`
        }
      }
    })
    return { whereSqlStrArr, tWhereSqlStrArr }
  }

  // function formatSql () {
  //   sqlStr.value = format(sqlStr.value)
  // }
  return {
    // formatSql,
    reBuildSql
  }
}
